<?php
/**
 * The Products Data Access Object. Retrieves Product Information from the Zen Cart database.
 * @copyright Nicolas Schudel 2008
 * @copyright Portions Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */

require_once(DTO_PATH . 'ProductDTO.php');

class ProductsDAO {
	private $db;
	private $cf;
	private $taxes;
	private $currencies;
	private $prices;
	
	function __construct() {
		$this->db = ServiceLocator::getService('ConnectionFactory');
		$this->cf = ServiceLocator::getService('Configuration');
		$this->taxes = ServiceLocator::getService('Taxes');
		$this->currencies = ServiceLocator::getService('Currencies');
		$this->prices = ServiceLocator::getService('Prices');
		$this->db->connect($this->cf->get('DB_SERVER'), $this->cf->get('DB_SERVER_USERNAME'), $this->cf->get('DB_SERVER_PASSWORD'), $this->cf->get('DB_DATABASE'), $this->cf->get('DB_USE_PCONNECT'), false);
	}
	
	private function getSingleProduct($pid) {
		// get the database contents as a ConnectionFactoryResult Object
		$productQuery = "SELECT p.products_id, pd.products_name, p.products_price, tr.tax_rate
						FROM ". $this->cf->get('TABLE_PRODUCTS') ." p, ". $this->cf->get('TABLE_PRODUCTS_DESCRIPTION') ." pd, ". $this->cf->get('TABLE_TAX_RATES') ." tr
						WHERE p.products_id = ". $pid ."
						AND p.products_id = pd.products_id
						AND tr.tax_class_id = p.products_tax_class_id
						AND pd.language_id = ". $this->cf->get('POS_DEFAULT_LANGUAGE_ID');
	
		$product = $this->db->execute($productQuery);
		
		// map the database result to the Data Transfer Object
		$dto = new ProductDTO();
		
		$dto->pid = round($product->fields['products_id']);
		$dto->name = utf8_encode($product->fields['products_name']);
		$dto->price = $this->taxes ->addTax($this->prices->getPrice($dto->pid), $product->fields['tax_rate']);
		
		return $dto;
	}
	
	public function find($pid){
		if (!$pid) {
			return false;
		} else if (is_array($pid)) {
			$products = array();
			foreach ($pid as $value) array_push($products, $this->getSingleProduct($value));
			return $products;
		} else {
			return $this->getSingleProduct($pid);
		}
	}
}
?>
